package com.wzh.mysending.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.wzh.mysending.StrongService;
import com.wzh.mysending.config.Constant;
import com.wzh.mysending.model.LocationEntity;
import com.wzh.mysending.model.UserEntity;
import com.wzh.mysending.utils.ServiceUtil;
import com.wzh.mysending.utils.loc.LocationUtil;
import com.wzh.mysending.utils.loc.OnGetLocationChanged;
import com.wzutils.NetUtils;
import com.wzutils.SPUtils;


import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * Created by Hu on 2017/3/22.
 */

public class MainService extends Service implements OnGetLocationChanged {
    private static final String TAG = "MainService====";
    private String Process_Name="com.wzh.mysending.service:keep";
    LocationUtil locationUtil;
    double lot = 0;
    double lat = 0;
    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG,"onCreate");
        initView();
        startKeppService();
    }
    private void initView() {
        locationUtil = new LocationUtil(getApplicationContext(), this);
    }
    /**
     *启动Service2
     */

   private StrongService startS2 = new StrongService.Stub() {
        @Override
        public void stopService() throws RemoteException {
            Intent i = new Intent(getBaseContext(),KeepService.class);
            getBaseContext().stopService(i);
        }

        @Override
        public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {

        }

        @Override
        public void startService() throws RemoteException {
            Intent i = new Intent(getBaseContext(), KeepService.class);
            getBaseContext().startService(i);
        }
    };

    private void startKeppService() {
        boolean isRun = ServiceUtil.isProessRunning(this, Process_Name);
        if (isRun == false) {
            try {
                //重新启动
                startS2.startService();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    public void onTrimMemory(int level){
        startKeppService();//保持Service2一直运行
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG,"onStartCommand");
        checkNet();
        return START_STICKY;
    }

    private void checkNet() {

        if (locationUtil==null){
            initView();
        }
        /**
         * 1、先进行是否有网络链接进行判断
         * 2、判断链接网络链接的方式
         * 3、判断是否是登录状态
         * 4、判断是否打开了定位
         *
         */
        if (NetUtils.isConnected(getApplicationContext())) {
            // TODO: 2017/3/21 记得反向
            if (!NetUtils.isWifi(getApplicationContext())) {
                boolean isHasLogin = SPUtils.contains(getApplicationContext(), Constant.ISLOGIN);
                boolean isHasOpen = SPUtils.contains(getApplicationContext(), Constant.ISOPEN);
                if (isHasLogin && isHasOpen) {
                    if ((boolean) SPUtils.get(getApplicationContext(), Constant.ISLOGIN, false) &&
                            (boolean) SPUtils.get(getApplicationContext(), Constant.ISOPEN, false)) {
                        locationUtil.startLocation();
                    }
                }
            }
        } else {
            locationUtil.stopLocation();
        }
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return (IBinder) startS2;
    }

    @Override
    public void onLocationOk(AMapLocation aMapLocation) {
        if (lat != aMapLocation.getLatitude() && lot != aMapLocation.getLongitude()) {
            Log.e("OK===",aMapLocation.toString());
            lat = aMapLocation.getLatitude();
            lot = aMapLocation.getLongitude();
            save(aMapLocation);
        }else {
            Log.e("OK===","重复");
        }
    }

    private void save(AMapLocation aMapLocation) {

        LocationEntity locationEntity = new LocationEntity();
        locationEntity.setLat(aMapLocation.getLatitude());
        locationEntity.setLot(aMapLocation.getLongitude());
        locationEntity.setAddRess(aMapLocation.getAddress());
        locationEntity.setSpeed(aMapLocation.getSpeed());

        locationEntity.setUserId(String.valueOf(SPUtils.get(getApplicationContext(), Constant.USER_ID, "")));
        locationEntity.setUserName(String.valueOf(SPUtils.get(getApplicationContext(), Constant.USER_NAME, "")));
        locationEntity.setUserPhone(String.valueOf(SPUtils.get(getApplicationContext(), Constant.PHONE, "")));

        final UserEntity userEntity = new UserEntity();
        userEntity.setLocationEntity(locationEntity);

        locationEntity.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null) {
                    Log.e("s====", "OK");
                    updateUserLocation(userEntity);
                } else {
                    Log.e("loc e====", e.toString());
                }
            }
        });
    }

    private void updateUserLocation(UserEntity userEntity) {
        userEntity.update(String.valueOf(SPUtils.get(getApplicationContext(), Constant.USER_ID, "")), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    Log.e("u====", "OK");
                } else {
                    Log.e("u e====", e.toString());
                }
            }
        });
    }

    @Override
    public void onLocationError(AMapLocation aMapLocation) {

        Log.e("err==", aMapLocation.toString());
    }

    @Override
    public void onLocationNull(AMapLocation aMapLocation) {

        Log.e("null==", aMapLocation.toString());
    }
}
